/**
 * Created with hong.rong
 * Description:*
 * Date:2020/06/29
 */

import axios from 'axios'
import { notification } from 'antd'
import { baseURL } from './config'

/**
 * 异常处理程序
 * @returns {*}
 */
const errorHandler = message => {
  notification.config({
    placement: 'topRight',
  })
  notification.error({
    message: '提示',
    description: message,
  })
}

// 创建axios实例
const instance = axios.create({
  baseURL: baseURL,
  timeout: 30000,
  withCredentials: false,
})

// 添加请求拦截器
instance.interceptors.request.use(
  config => {
    if (
      !config.url.includes('/admin/verCode') &&
      !config.url.includes('/admin/login')
    ) {
      config.headers.token = localStorage.getItem('token')
    }
    return config
  },
  error => {
    return Promise.reject(error)
  }
)

// 添加响应拦截器
instance.interceptors.response.use(
  response => {
    const data = response.data || {}
    console.log(data, 'data')
    if (data.code && data.code !== 0) {
      errorHandler(data.msg)
    }
    return response
  },
  error => {
    console.log(error, 'error')
    // 全局抛错
    errorHandler('网络异常')
    return Promise.reject(error)
  }
)

export default instance
